package cn.satoken.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.satoken.entity.CrmDeptment;
import cn.satoken.entity.SysUser;
import cn.satoken.entity.SysUserRole;
import cn.satoken.mapper.DeptmentMapper;
import cn.satoken.mapper.SysUserMapper;
import cn.satoken.service.SysUserRoleService;
import cn.satoken.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.satoken.common.ValueValid.ensureColumnValueValid;
import static cn.satoken.constant.StatusConstant.*;

/**
 * <h3>saToken</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-04-21 16:51:10
 */
@RestController
@RequestMapping("/user/")
@RequiredArgsConstructor
public class UserController {
    private final SysUserMapper sysUserMapper;
    private final SysUserService sysUserService;
    private final SysUserRoleService sysUserRoleService;
    private final DeptmentMapper deptmentMapper;
    private final SimpMessagingTemplate messagingTemplate;
    @Value("${pasword.key}")
    private String paswordKey;

    /**
     * 保存用户
     * @param user
     * @return
     */
    @PostMapping("save")
    public SaResult save(@RequestBody SysUser user) {
        if(user.getId()!=null){
            user.setPassword(user.getPassword()!=null? SaSecureUtil.aesDecrypt(paswordKey,user.getPassword()):null);
            sysUserMapper.updateById(user);
            LambdaUpdateWrapper<SysUserRole> wrapper=new LambdaUpdateWrapper<>();
            wrapper.eq(SysUserRole::getUserId, user.getId())
                    .set(SysUserRole::getRoleId,user.getRoleId());
            sysUserRoleService.update(wrapper);
            return SaResult.ok(UPDATE_SUCCESS);
        }else{
            ensureColumnValueValid(user.getPhone(), SysUser::getPhone, sysUserMapper::selectOne,PHONE_REPEAT_ERRO);
            user.setStatus(1);
            SaSecureUtil.aesDecrypt(paswordKey,user.getPassword());
            sysUserMapper.insert(user);
            //保存角色信息
            sysUserRoleService.save(new SysUserRole(user.getId(), user.getRoleId()));
            return SaResult.ok(SAVE_SUCCESS);
        }
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @GetMapping("deleteById/{id}")
    public SaResult deleteById(@PathVariable("id") String id) {
        if(!ensureColumnValueValid(id,SysUser::getId, sysUserMapper::selectOne)) return SaResult.error(SELECT_ID_DATA_ERRO);
        sysUserMapper.deleteById(id);
        return SaResult.ok(DELETE_SUCCESS);
    }
    /**
     * 踢人下线
     *
     */
    @GetMapping("loginOutApi/{id}")
    public SaResult loginOutApi(@PathVariable("id") String id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        StpUtil.kickout(id,"PC");
        messagingTemplate.convertAndSend("/topic/login",sysUser.getName()+"用户，被踢下线！");
        return SaResult.ok("踢人下线成功");
    }

    /**
     * 根据部门id查询用户
     * @param deptId
     * @return
     */
    @GetMapping("findByDeptId/{deptId}")
    public SaResult findByDeptId(@PathVariable("deptId") Long deptId) {
        return sysUserService.findByDeptId(deptId);
    }

    /**
     * 分页查询
     */
    @GetMapping("page")
    public SaResult selectPage(@RequestParam int page, @RequestParam int size,@RequestParam Map<String, Object> map) {
        if(page <= 0 || size <= 0) {
            page = 1;
            size = 10;
        }
        String name = map.get("name") != null ? map.get("name").toString() : null;
        Long deptId = map.get("deptId") != null ? Long.parseLong(map.get("deptId").toString()) : null;
        Map<String, Object> condition = new HashMap<>();
        condition.put("name", name);
        condition.put("deptId", deptId);
        return sysUserService.selectPage(page,size,condition);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("deleteBatch")
    public SaResult deleteBatch(@RequestBody List<Long> ids) {
        for (Long id : ids) {
            if (StpUtil.isLogin(id)){
                StpUtil.logout(id);
            }
        }
        sysUserMapper.deleteBatchIds(ids);
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SysUserRole::getUserId, ids);
        sysUserRoleService.remove(wrapper);
        return SaResult.ok(DELETE_SUCCESS);
    }
    @GetMapping("selectAll")
    public SaResult selectAll() {
        List<SysUser> sysUsers = sysUserMapper.selectList(null);
        for (SysUser sysUser : sysUsers) {
            CrmDeptment crmDeptment = deptmentMapper.selectById(sysUser.getDeptId());
            sysUser.setDeptName(crmDeptment.getName());
        }
        return SaResult.data(sysUsers);
    }

}
